<template>

<div class="f-ab" style="overflow:hidden;">
  
  <!-- 应用头部 -->
  <header-zone class="f-ab g-header">
    <div slot="btn-center">       

    </div>  
    <div slot="btn-right">
      <button class="btn btn-danger btn-sm" @click="toggleDebug">
        调试
      </button>    
      <button class="btn btn-info btn-sm" @click="setApp">
        设置
      </button>      
      <button class="btn btn-success btn-sm" @click="saveH5">
        <i class="icon-save"></i> 预览
      </button>
      <button class="btn btn-primary btn-sm" @click="previewH5">
        <i class="icon-camera-retro"></i> 发布
      </button>   
    </div>
  </header-zone>

  <div class="f-ab g-content">
    
    <!-- 页面管理区域 -->
    <layer-zone 
      :pages.sync="slide.pages" 
      :active-page-index.sync="activePageIndex">
    </layer-zone>

    <!-- 编辑区域 -->
    <canvas-zone 
      :slide.sync="slide"
      :show-picture-dialog.sync="showPictureDialog"
      :current-page.sync="currentPage"
      :current-comp.sync="currentComp">
    </canvas-zone>

    <!-- 工具区域 -->
    <edit-zone 
      :slide.sync="slide"
      :current-page.sync ="currentPage" 
      :current-comp.sync = "currentComp">
    </edit-zone>
  </div>

  <!-- 预览 h5 弹窗 -->
  <preview-zone 
    :show.sync="showPreviewDialog" 
    :id="id">
  </preview-zone>
  
  <!-- 编辑信息弹窗 -->
  <dialog :show.sync="showSetingDialog" title="h5 设置" :width="700">
    <setting-zone 
      slot="content"
      :title.sync="slide.title"
      :description.sync="slide.description"
      :icon.sync="slide.icon"
      :show.sync="showSetingDialog"
      >
    </setting-zone>
  </dialog>

  <!-- 后台编辑信息弹窗 -->
  <dialog :show.sync="showAdminSetingDialog" title="完善信息" :width="600">
    <admin-setting-zone class="test"
      slot="content"
      :title.sync="slide.title"
      :description.sync="slide.description"
      :icon.sync="slide.icon"
      :tags.sync="slide.tags"
      :show.sync="showAdminSetingDialog"
      >
    </admin-setting-zone>
  </dialog>

  <!-- 表单选择弹窗 -->
  <form-zone 
    :show.sync="showFormZoneDialog">
  </form-zone>

  <!-- 图片选择弹窗  -->
  <picture-dialog 
    :show.sync="showPictureDialog"
    :type="pictureDialogType">
  </picture-dialog>

</div>
</template>

<script>
var todoStorage = {
  prefix: 'hy-sms-h5', 
  fetch: function (name) {
    return JSON.parse(localStorage.getItem(this.prefix + '_' + name) || null);
  },
  save: function (name, todos) {
    localStorage.setItem(this.prefix + '_' +name, JSON.stringify(todos));
  }
};
var defautPageSetting = function() {
  return {
    style: {
      backgroundColor: '#ffffff',
      image: null
    },
    comps:[]
  }
};
export default {
  data: function(){
    return {
      id: null,
      slide: {
        title: '我的h5作品',
        description: "我的h5作品, 有没有觉得很高大上啊~快来膜拜我！",
        icon: '/static/img/icon.png',
        tags: '',
        music: {},
        pages: [ defautPageSetting() ]
      },
      tpl: -1,
      template: false,
      release: -1,
      activePageIndex:  0,
      currentComp: {
        type: 'hy-page'
      },
      showSetingDialog: false,
      showAdminSetingDialog: false,
      showPictureDialog: false,
      pictureDialogType: "",
      showPreviewDialog: false,
      showFormZoneDialog: false
    }
  },
  computed: {
    currentPage: function(){
      var len = this.slide.pages.length;
      if( this.activePageIndex >= len ){
        this.activePageIndex = len - 1;
      }
      return this.slide.pages[this.activePageIndex];
    },
    isAdmin: function(){
      return false;
    }    
  }, 
  created: function(){
    var _this = this;
    var query  = window.GetUrlParms();
    var id = location.hash.replace('#','');
    if( id ) {
      $.ajax({
        url: Global.api.h5 + "/" + id,
        method: "GET",
        dataType: "json",
        success: function(result){
          if( result.status === 0 ){
            var h5 = result.data;
            var h5Data = JSON.parse(h5.data);
            _this.id = h5._id;
            _this.slide = h5Data.slide;
            _this.activePageIndex = h5Data.activePageIndex;
          }
        }
      });
    }
  }, 
  methods: {
    // 设置h5信息
    setApp: function(){
      if(this.isAdmin){
        this.showAdminSetingDialog = true;
      }
      else {
        this.showSetingDialog = true;
      }
    },
    // 新建h5或者编辑h5
    save: function(){
      var data = {
        title: this.slide.title,
        decription: this.slide.description,
        icon: this.slide.icon,
        data: JSON.stringify(this.$data),
        tpl: this.tpl,
        template: this.template,
        release: this.release,
        tags: this.slide.tags
      };
      // 编辑
      if( this.id ) {
        return $.ajax({
          url: Global.api.h5 + "/" + this.id ,
          method: "PUT", 
          data: data,
          dataType: "json"
        });
      }
      // 新建
      else {
        return $.ajax({
          url: Global.api.h5 ,
          method: "POST", 
          data: data,
          dataType: "json"
        });
      }
    },
    // 保存
    saveH5: function(){
      var _this = this;
      this.save()
        .success(function(result){
          if(result.status === 0){
            _this.id = result.data._id;
            _this.showPreviewDialog = true;
          }
          else{
            layer.alert('保存失败')
          }
        })
        .error(function(data){
          layer.alert('保存失败');
        })
    },
    // 保存并预览
    previewH5: function(){
      var _this = this;
      _this.save()
        .success(function(result){
          if(result.status === 0 ){
            _this.id = result.data._id;
            layer.alert('发布成功');
          }
          else{
            layer.alert('保存失败');
          }        
        })
        .error(function(result){
          console.log(result);
          layer.alert('保存失败');
        });        
    },
    // 打开debug 
    toggleDebug: function(){
      this.$broadcast('toggle-debug');
    }
  },
  watch:{
    id: {
      handler: function (id) {
        location.hash = id;
      }
    }
  },
  events: {
    'showPictureDialog': function(type){
     this.showPictureDialog = true;
     this.pictureDialogType = type;
    },
    'addImageComp': function (imgSrc) {
      if (this.currentPage) {
        this.currentPage.comps.push({
          type: 'hy-image',
          active: true,
          isShowView: true,
          isShowEdit: true,
          imgSrc: imgSrc,
          isShowAnimate: false,
          animate: {
            name: "none",
            duration: 1,
            delay: 0
          },
          zIndex: 0,
          position: {
            left: 60,
            top: 100,
            width: 200,
            height: 'auto',
            transform: 0
          },
          style: {
            opacity: 1,
            borderRadius: 0,
            boxShadow: 0,
          }
        });
        var len = this.currentPage.comps.length;
        this.currentComp = this.currentPage.comps[len - 1];
      }
    },
    'changeAppIcon': function (imgSrc) {
      this.slide.icon = imgSrc;
    },
    'showFormZone': function(){
      this.showFormZoneDialog = true;
    },
    'addformComp': function(type){
      var list = null;
      switch(type){
        case 0:
          list = [{
            type:'xText',
            name:'姓名',
            required: true
          },{
            type:'xText',
            name:'手机',
            required: true
          },{
            type:'xText',
            name:'邮箱',
            required: false
          }];        
        break;        
        case 1:
          list = [{
            type:'xStar',
            name:'五星评价',
            defualt: 0
          }];         
        break;
        case 2:
          list = [{
            type:'xRadio',
            name:'请输入问题',
            items: ["选项一", "选项二","选项三"]
          }];         
        break;
        case 3:
          list = [{
            type:'xCheckbox',
            name:'请输入问题',
            items: ["选项一", "选项二","选项三"]
          }];         
        break;
        default:
          throw new Errow('错误, 未知表单模版类型');
      }
      if(this.currentPage){
        this.currentPage.comps.push({
          type: 'hy-form',
          active: false,
          isShowView: true,
          isShowEdit: true,  
          isShowAnimate: false,
          btn: {
            text:'提交',
          },
          feedback:{
            text: '提交成功！感谢你的参与'
          },
          list: list,
          animate:{
            name: "none",
            duration: 1,
            delay: 0
          },
          position:{
            left: 0,
            top: 0,
            width: 280,
            height: 340,
            transform: 0
          },
          style: {
            backgroundColor: '#ffffff',
            borderWidth: 0,
            borderColor: '#cccccc',
            borderStyle: 'solid',
            borderRadius: 0,
            opacity: 1,
            fontWeight: 'normal',
            fontStyle: 'normal',
            textDecoration: 'normal',
            textAlign: 'center'
          }          
        });
        var len = this.currentPage.comps.length;
        this.currentComp = this.currentPage.comps[len -1 ];            
      }
    }
  },  
  components : {
    headerZone  : require('./headerZone.vue'),
    layerZone   : require('./layerZone.vue'),
    canvasZone  : require('./canvasZone.vue'),
    editZone    : require('./editZone.vue'),
    previewZone : require('./previewZone.vue'),
    settingZone : require('./settingZone.vue'),
    formZone : require('./formZone.vue'),
    adminSettingZone : require('./adminSettingZone.vue'),
    dialog      : require('./plugin/dialog.vue'),
    pictureDialog : require('./plugin/pictureDialog.vue')
  }
}
</script>